package com.sap.test;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@SpringBootTest
public class MyThread {

    private Integer total = 100;

    @Test
    public void test() {
        ExecutorService pool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            pool.submit(() -> {
                while (true) {
                    synchronized (total) {
                        total--;
                    }
                    System.out.println(Thread.currentThread().getName() + "剩余票数：" + total);
                    if (total <= 0) {
                        break;
                    }
                }
            });
        }
        pool.shutdown();

    }

    @Test
    public void test1() {
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        synchronized (total) {
                            total--;
                        }
                        System.out.println(Thread.currentThread().getName() + "剩余票数：" + total);
                        if (total <= 0) {
                            break;
                        }
                    }
                }
            }).start();
        }
    }

    @Autowired
    @Qualifier("customThreadPool") // 如果有多个线程池，需指定名称
    private ThreadPoolTaskExecutor taskExecutor;

    @Test
    public void test2() {
        for (int i = 0; i < 10; i++) {
            taskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        synchronized (total) {
                            total--;
                            System.out.println(Thread.currentThread().getName() + "剩余票数：" + total);
                            if (total <= 0) {
                                break;
                            }
                        }

                    }
                }
            });
        }
    }

    @Test
    public void test3() {

    }
}
